package com.cloudcc.mobile.view.attendance;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.AttendanceEntity;
import com.cloudcc.mobile.event.AttendanceEventList.AttendanceHomeEvent;
import com.cloudcc.mobile.event.AttendanceEventList.CheckResultEvent;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.presenter.AttendancePresenter;
import com.cloudcc.mobile.presenter.AttendancePresenter.AttendanceHomeEntity;
import com.cloudcc.mobile.util.PopuWindowUtils;
import com.cloudcc.mobile.util.ViewUtils;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.weight.DialogUtils;
import com.cloudcc.mobile.weight.DialogUtils.DialogOnClickListener;
import com.cloudcc.mobile.widget.fancybuttons.FancyButton;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AttendanceMainFragment extends BaseFragment {

    @Bind(R.id.attendance_timeImg)
    ImageView attendance_timeImg;
    @Bind(R.id.attendance_locationImg)
    ImageView attendance_locationImg;
    @Bind(R.id.attendance_qt_timeImg)
    ImageView attendance_qt_timeImg;
    @Bind(R.id.attendance_qt_locationImg)
    ImageView attendance_qt_locationImg;

    private String mEns = RunTimeManager.getInstance().getlanguage();
    /**
     * 内勤
     */
    private static final int TYPE_INNER = 1;
    /**
     * 外勤
     */
    private static final int TYPE_OUTTER = 2;

    private static final int OPS_CHECK_LOGIN = 1;// 操作 签到

    private static final int OPS_CHECK_LOGINOUT = 2;// 签退

    private static final int OPS_LOC = 3;// 定位
    @Bind(R.id.indexselect)
    RelativeLayout indexselect;// 上面的选择框
    @Bind(R.id.textView1)
    TextView title;

    // 标题
    @Bind(R.id.attendance_title)
    TextView attendance_title;

    @Bind(R.id.attendance_time)
    TextView attendance_time;

    @Bind(R.id.attendance_location)
    TextView attendance_location;
    @Bind(R.id.attendance_qt_title)
    TextView attendance_qt_title;
    @Bind(R.id.attendance_qt_time)
    TextView attendance_qt_time;
    @Bind(R.id.attendance_qt_location)
    TextView attendance_qt_location;
    @Bind(R.id.attendance_now)
    TextView attendance_now;

    @Bind(R.id.attendance_qd_check)
    FancyButton btn_checkIn;

    @Bind(R.id.attendance_qd_check_)
    ImageView attendance_qd_check_;

    @Bind(R.id.attendance_qd_out_)
    ImageView attendance_qd_out_;

    @Bind(R.id.attendance_qd_location_)
    ImageView attendance_qd_location_;

    private int attendanceTypeIndex = 1;// 默认是 内勤

    private int mCurrentOpsIndex = -1;

    private AttendancePresenter mAttendancePresenter = new AttendancePresenter();

    private AttendanceHomeEntity mHomeEntity;

    @Override
    public void init() {
        super.init();
        initView();
        showWainting();
        refreshHome();
    }
    public void initView(){
        if ("en".equals(mEns)){
            attendance_qd_check_.setImageResource(R.drawable.aaqian_dao_en);
            attendance_qd_out_.setImageResource(R.drawable.aaqian_tui_en);
        }else{
            attendance_qd_check_.setImageResource(R.drawable.aaqian_dao);
            attendance_qd_out_.setImageResource(R.drawable.aaqian_tui);
        }

    }
    private void setShowOrHint() {
        String mTimea = attendance_time.getText().toString();
        String mWeia = attendance_location.getText().toString();
        String mTimeb = attendance_qt_time.getText().toString();
        String mWeib = attendance_qt_location.getText().toString();
        if (mTimea == null || mTimea == "") {
            attendance_timeImg.setVisibility(View.GONE);
            attendance_locationImg.setVisibility(View.GONE);
            attendance_qt_timeImg.setVisibility(View.GONE);
            attendance_qt_locationImg.setVisibility(View.GONE);
        }else{
            attendance_timeImg.setVisibility(View.VISIBLE);
            attendance_locationImg.setVisibility(View.VISIBLE);
            attendance_qt_timeImg.setVisibility(View.VISIBLE);
            attendance_qt_locationImg.setVisibility(View.VISIBLE);
        }
    }

    private void refreshHome() {
        mAttendancePresenter.queryHome();
    }

    @OnClick(R.id.indexselect)
    public void onClickIndex() {
        showWindow();
    }

    @OnClick(R.id.attendance_qd_check_)
    public void onClickCheckIn() {
        // #1 看看有位置吗 没有的话 定位啊
        mCurrentOpsIndex = OPS_CHECK_LOGIN;
        if (null == lastDBLocation) {// 无定位数据 先去定位

            startLocal(true);
        } else {
            showCheckInResult();
        }
    }

    @OnClick(R.id.attendance_qd_out_)
    public void onClickOut() {
        // 签退
        mCurrentOpsIndex = OPS_CHECK_LOGINOUT;
        if (null == lastDBLocation) {
            startLocal(true);
        } else {// 已经存在定位数据
            showCheckOutResult();
        }
    }

    @OnClick(R.id.attendance_qd_location_)
    public void onClickLoc() {
        mCurrentOpsIndex = OPS_LOC;
        startLocal(true);
    }

    public void onEventMainThread(CheckResultEvent event) {
        String q = "签";
        String d = "到";
        String t = "退";
        String fail = "失败";
        String succ = "成功";


        if ("en".equals(mEns)) {
            q = "sign";
            d = "To";
            t = "Retreat";
            fail = "failure";
            succ = "success";

        } else {
            q = "签";
            d = "到";
            t = "退";
            fail = "失败";
            succ = "成功";

        }

        String ops = q;
        if (mCurrentOpsIndex == OPS_CHECK_LOGIN) {
            ops += d;
        } else {
            ops += t;
        }
        dismissWainting();
        if (event.isError()) {
            showToast(ops + fail + "(" + event.getMessage() + ")");
            return;
        }
        showToast(ops + succ);
        refreshHome();

    }

    public void onEventMainThread(AttendanceHomeEvent event) {
        dismissWainting();
        if (event.isError()) {
            if ("en".equals(mEns)) {
                showToast("initialization failed。。。");
            } else {
                showToast("初始化失败。。。");
            }

            getActivity().finish();
            return;
        }
        mHomeEntity = event.getData();

        fillUI();

    }

    /**
     * 今天是否已经签到
     *
     * @return 2016-4-29
     */
    private boolean hasCheckInToday() {
        if (null != mHomeEntity && mHomeEntity.todaycheck != null
                && StringUtils.isNotBlank(mHomeEntity.todaycheck.qdsj))
            return true;
        return false;
    }

    @Override
    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
        return super.getLayoutInflater(savedInstanceState);
    }

    private void fillUI() {
        if (null == mHomeEntity || mHomeEntity.todaycheck == null) {
            return;
        }
        AttendanceEntity todaycheck = mHomeEntity.todaycheck;

        ViewUtils.setText(attendance_now, todaycheck.rq);
        if ("en".equals(mEns)) {
            ViewUtils.setText(attendance_title, hasCheckIn() ? "Sign in" : "Not sign in");
        } else {
            ViewUtils.setText(attendance_title, hasCheckIn() ? "已签到" : "未签到");
        }

        ViewUtils.setText(attendance_time, todaycheck.qdsj);
        ViewUtils.setText(attendance_location, todaycheck.qdwz);
        if ("en".equals(mEns)) {
            ViewUtils.setText(attendance_qt_title, hasCheckOut() ? "Sign out" : "Not checked out");
        } else {
            ViewUtils.setText(attendance_qt_title, hasCheckOut() ? "已签退" : "未签退");
        }

        ViewUtils.setText(attendance_qt_time, todaycheck.qtsj);
        ViewUtils.setText(attendance_qt_location, todaycheck.qtwz);

        //注销的是之前的
//		if (hasCheckInToday()) {
//            attendance_qd_check_.setBackgroundColor(mContext.getResources().getColor(
//					R.color.gray_pressed));
//            attendance_qd_check_.setEnabled(false);
//		} else {
//            attendance_qd_check_.setBackgroundColor(Color.parseColor("#55acee"));
//            attendance_qd_check_.setEnabled(true);
//		}
        setShowOrHint();
    }

    /**
     * 是否已经签到
     *
     * @return
     */
    private boolean hasCheckIn() {
        if (null == mHomeEntity
                || mHomeEntity.todaycheck == null
                || (StringUtils.isBlank(mHomeEntity.todaycheck.qdsj) && StringUtils
                .isBlank(mHomeEntity.todaycheck.qdzb)))
            return false;
        return true;
    }

    /**
     * 是否已经签退
     *
     * @return 已经签退
     */
    private boolean hasCheckOut() {
        if (null == mHomeEntity
                || mHomeEntity.todaycheck == null
                || (StringUtils.isBlank(mHomeEntity.todaycheck.qtsj) && StringUtils
                .isBlank(mHomeEntity.todaycheck.qtzb)))
            return false;
        return true;
    }

    /**
     * 签到或者签退
     */
    private void check(int checkInOrOut) {
        showWainting();
        if (null == lastDBLocation) {
            dismissWainting();
            if ("en".equals(mEns)) {
                showToast("Please reposition...");
            } else {
                showToast("请重新定位...");
            }

            return;
        }

        // 非空 判断
        if (null == mHomeEntity || null == mHomeEntity.checkloc) {
            dismissWainting();
            if ("en".equals(mEns)) {
                showToast("Parameter error...");
            } else {
                showToast("参数错误...");
            }

            return;
        }

        int userAttTypeNumber = getUserAttTypeNumber();
        if (userAttTypeNumber == 1) {// 内勤外勤都能签到
            checkToNet(checkInOrOut);
        } else if (userAttTypeNumber == 2) {// 只能签到外勤
            if (attendanceTypeIndex == TYPE_INNER) {
                dismissWainting();
                if ("en".equals(mEns)) {
                    showToast("Sorry, the current only allows you to sign in the field...");
                } else {
                    showToast("对不起,当前只允许你签到外勤...");
                }

            } else {
                checkToNet(checkInOrOut);
            }
        } else if (userAttTypeNumber == 3) {// 存在坐标点
            /*
             * 1、内勤用户 签到 内勤 判断距离 签到外勤 不用判断距离 2、外勤用户 签到 内勤 判断距离 签到外勤 判断距离
			 */
            if (2 == mHomeEntity.checkloc.type) {// 外勤用户
                // 判断距离
                boolean inCenter = isInCenter();
                if (inCenter) {
                    checkToNet(checkInOrOut);
                }
            } else if (1 == mHomeEntity.checkloc.type) {// 内勤用户
                if (attendanceTypeIndex == TYPE_INNER) {
                    boolean inCenter = isInCenter();
                    if (inCenter) {
                        checkToNet(checkInOrOut);
                    }
                } else {
                    checkToNet(checkInOrOut);
                }
            }

        }
    }

    /**
     * 是否满足 在 坐标点范围内
     *
     * @param
     * @return 2016-4-27
     */
    private boolean isInCenter() {
        if (mHomeEntity.checkloc.deviation <= 0) {
            mHomeEntity.checkloc.deviation = 200;
        }

        int betweenCenter = distanceBetweenCenter();

        if (mHomeEntity.checkloc.deviation < betweenCenter) {
            dismissWainting();
            if ("en".equals(mEns)) {
                showToast("Not allowed to sign, the difference:" + String.valueOf((int) betweenCenter));
            } else {
                showToast("不允许签到,相差:" + String.valueOf((int) betweenCenter));
            }

            return false;
        }
        return true;

    }

    /**
     * 计算
     *
     * @return 2016-4-27
     */
    private int distanceBetweenCenter() {

        if (lastDBLocation == null || mHomeEntity.checkloc.lat <= 0
                || mHomeEntity.checkloc.lon <= 0) {
            return -1;
        }

        LatLng latlngMy = new LatLng(lastDBLocation.getLatitude(),
                lastDBLocation.getLongitude());
        LatLng latlngCenter = new LatLng(mHomeEntity.checkloc.lat,
                mHomeEntity.checkloc.lon);

        double distance = DistanceUtil.getDistance(latlngMy, latlngCenter);
        return (int) distance;
    }

    /**
     * 签到签退
     *
     * @param checkInOrOut 2016-4-27
     */
    private void checkToNet(int checkInOrOut) {
        String addr = LocationManager.getDetailAddr(lastDBLocation, false);
        mAttendancePresenter.check(
                String.valueOf(lastDBLocation.getLongitude()),
                String.valueOf(lastDBLocation.getLatitude()),
                String.valueOf(attendanceTypeIndex), addr, checkInOrOut);
    }

    /**
     * 获得当前用户的签到类型
     *
     * @return 1 :-1类型 <br>
     * 2:null<br>
     * 3:有坐标点 2016-4-27
     */
    private int getUserAttTypeNumber() {

        if (null == mHomeEntity || mHomeEntity.checkloc == null) {
            return -1;// 还没有获取到 今日的签到信息
        }
        if (mHomeEntity.checkloc.lat == 0.0 || mHomeEntity.checkloc.lon == 0.0) {
            return 2;
        }
        if (mHomeEntity.checkloc.lat < 0 || mHomeEntity.checkloc.lon < 0) {
            return 1;
        }
        if (mHomeEntity.checkloc.lat > 0 && mHomeEntity.checkloc.lon > 00) {
            return 3;
        }
        return 0;
    }

    /**
     * 服务器是否配置了签到中心点
     *
     * @return 2016-3-30
     */
    private boolean hasCheckCenter() {
        return null != mHomeEntity && null != mHomeEntity.checkloc
                && mHomeEntity.checkloc.lat > 0 && mHomeEntity.checkloc.lon > 0;
    }

    private boolean shouldShowWaiting = false;// 是否显示dialog 在定位的时候

    /**
     * 开始定位
     *
     * @param isShowWaiting 是否显示 定位进行的时候的dialog 提示
     */
    private void startLocal(boolean isShowWaiting) {
        shouldShowWaiting = isShowWaiting;
        if (isShowWaiting) {// 显示定位的等待提示
            if ("en".equals(mEns)) {
                showDialogTy("Is positioning, please wait...");
            } else {
                showDialogTy("正在定位,请稍等...");
            }

        }
        LocationManager.getInstance().registerListener(mListener);
        LocationManager.getInstance().requestLocal();
    }

    /**
     * 定位结束的时候
     *
     * @param success 是否定位成功
     */
    private void onLocalFinish(boolean success) {
        if (shouldShowWaiting) {// 刚才显示dialog 了 取消吊
            dismissWainting();
        }
        if (!success) {
            if ("en".equals(mEns)) {
                showToast("Location failed, please try again");
            } else {
                showToast("定位失败,请重试");
            }


            return;
        }
        switch (mCurrentOpsIndex) {
            case 1:// 签到
                showCheckInResult();
                break;
            case 2:// 签退
                showCheckOutResult();
                break;
            case 3:// 定位
                showLocResult();
                break;

        }
    }

    /**
     * 显示点击显示的结果 2016-4-22
     */
    private void showCheckInResult() {
        showLocalResult(new DialogOnClickListener() {
            @Override
            public void onClickPositive(Dialog dialog) {
                dialog.cancel();
                check(1);
            }

            @Override
            public void onClickNegative(Dialog dialog) {
                dialog.cancel();
            }
        });
    }

    private void showCheckOutResult() {
        showLocalResult(new DialogOnClickListener() {
            @Override
            public void onClickPositive(Dialog dialog) {
                dialog.cancel();
                check(2);
            }

            @Override
            public void onClickNegative(Dialog dialog) {
                dialog.cancel();
            }
        });
    }

    private void showLocResult() {
        showLocalResult(new DialogOnClickListener() {
            @Override
            public void onClickPositive(Dialog dialog) {
                dialog.cancel();
            }

            @Override
            public void onClickNegative(Dialog dialog) {
                dialog.cancel();
            }
        });
    }

    /**
     * 显示 当前位置dialog
     */
    private void showLocalResult(DialogOnClickListener l) {
        String addr = LocationManager.getDetailAddr(lastDBLocation, true);

        // 计算 距离
        String distanceStr = "";
        if (null != lastDBLocation
                && hasCheckCenter()
                && (!(attendanceTypeIndex == TYPE_OUTTER && mHomeEntity.checkloc.type == 1))) {// 存在坐标点
            // 的时候才显示
            // 距离
            LatLng lastLatLng = new LatLng(lastDBLocation.getLatitude(),
                    lastDBLocation.getLongitude());
            LatLng latLng = new LatLng(mHomeEntity.checkloc.lat,
                    mHomeEntity.checkloc.lon);
            double distance = DistanceUtil.getDistance(lastLatLng, latLng);
            distanceStr = "距离签到点:" + String.valueOf((int) distance) + "m";
        }

        if (TextUtils.isEmpty(addr)) {
            return;
        }
        String message = addr + "\n" + distanceStr;
        try {
            if ("en".equals(mEns)) {
                DialogUtils.showWarn(mContext, "prompt", message, l);
            } else {
                DialogUtils.showWarn(mContext, "提示", message, l);
            }

        } catch (Exception e) {
        }
    }

    private PopupWindow attendanceType;

    private void showWindow() {
        PopuWindowUtils.dissmiss(attendanceType);
        RadioGroup group = (RadioGroup) LayoutInflater.from(getActivity())
                .inflate(R.layout.attendance_type_pop, null);
        WindowManager wm = getActivity().getWindowManager();
        int width = wm.getDefaultDisplay().getWidth() / 2;
        attendanceType = new PopupWindow(group, width,
                LayoutParams.WRAP_CONTENT);
        attendanceType.setFocusable(true);
        attendanceType.setOutsideTouchable(true);
        attendanceType.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));

        int xPos = indexselect.getWidth() / 2 - attendanceType.getWidth() / 2;
        attendanceType.showAsDropDown(indexselect, xPos, 12);
        group.check(attendanceTypeIndex == 1 ? R.id.attendance_type_in
                : R.id.attendance_type_out);
        group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkId) {

                if (checkId == R.id.attendance_type_in) {
                    attendanceTypeIndex = TYPE_INNER;
                } else {
                    attendanceTypeIndex = TYPE_OUTTER;

                }
                PopuWindowUtils.dissmiss(attendanceType);
                RadioButton rbN = (RadioButton) arg0.findViewById(checkId);
                title.setText(rbN.getText());
            }
        });
    }

    private BDLocation lastDBLocation;// 最新的定位位置
    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location
                    && location.getLocType() != BDLocation.TypeServerError) {
                lastDBLocation = location;
                LocationManager.getInstance().stopRequestLocal();
                LocationManager.log(lastDBLocation);
                onLocalFinish(true);
            } else {
                if (null != location) {
                    if ("en".equals(mEns)) {
                        showToast("Positioning failed, please try again! Error code:" + location.getLocType());
                    } else {
                        showToast("定位失败，请重试! 错误码:" + location.getLocType());
                    }

                }
                onLocalFinish(false);
            }
        }
    };

    public void onDestroy() {
        LocationManager.getInstance().unregisterlistener(mListener);
        super.onDestroy();
    }

    ;

    @Override
    public int getLayoutId() {
        return R.layout.attendance_main;
    }

    @OnClick(R.id.back)
    public void onclickBack() {
        getActivity().finish();
    }

    @OnClick(R.id.right_text)
    public void onclickRight() {
        Intent intent = new Intent(mContext, AttendanceHistoryActivity.class);
        startActivity(intent);
    }

    @Override
    protected boolean hasEventLife() {
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
